package top.lshaci.learning.netty.tcp;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * TcpServer
 *
 * @author lshaci
 * @since 1.0.0
 */
public class TcpClient {

    public static void main(String[] args) {
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            Bootstrap client = new Bootstrap();
            client.group(worker)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            final ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MessageDecoder());
                            pipeline.addLast(new MessageEncoder());
                            pipeline.addLast(new SimpleChannelInboundHandler<MessageProtocol>() {

                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    for (int i = 0; i < 10; i++) {
                                        String msg = i + ": 天气冷，吃火锅";
                                        byte[] content = msg.getBytes(CharsetUtil.UTF_8);
                                        MessageProtocol messageProtocol = new MessageProtocol(content.length, content);
                                        ctx.writeAndFlush(messageProtocol);
                                    }
                                }

                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
                                    byte[] content = msg.getContent();
                                    String s = new String(content, CharsetUtil.UTF_8);
                                    System.err.println("接收到消息：" + s);
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                    cause.printStackTrace();
                                    ctx.close();
                                }
                            });
                        }
                    });
            final ChannelFuture future = client.connect("localhost", 7000).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
